package node;

/*
    You are given two non-empty linked lists representing two non-negative integers.
    The digits are stored in reverse order and each of their nodes contain a single digit.
     Add the two numbers and return it as a linked list.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Example:

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.

 */
public class AddTwoNumber {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode dummyNode = new ListNode(0);

        ListNode temp1 = l1;
        ListNode temp2 = l2;
        ListNode curr = dummyNode;

        int carry = 0; //进位

        while (temp1!=null || temp2!=null){

            int x = temp1==null?0:temp1.val;
            int y = temp2==null?0:temp2.val;

            int result = (x+y+carry)%10;
            carry = (x+y+carry)/10;
            curr.next=new ListNode(result);
            curr = curr.next;
            if(temp1!=null) temp1=temp1.next;
            if(temp2!=null) temp2=temp2.next;
        }

        if(carry>0){
            curr.next = new ListNode(carry);
        }

        return dummyNode.next;
    }

}
